package com.flea.system.platform.session;

import com.flea.hclv.constant.HConstant;
import com.flea.system.entity.OrgDept;
import com.flea.system.entity.OrgRole;
import com.flea.system.entity.OrgUser;
import com.flea.system.security.ILoginInfo;
import com.flea.system.service.IOrgDeptService;
import com.flea.system.service.IOrgDeptUserService;
import com.flea.system.service.IOrgRoleUserService;
import com.flea.system.service.IOrgUserService;
import com.flea.system.utils.FleaWordServiceUtils;
import flea.sys.cache.FleaCacheUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 与获取当前用户有关
 *
 * @author xiang
 */
public class FleaOrgUtils {
    private static Logger logger = LoggerFactory.getLogger(FleaOrgUtils.class);
    private static String userUuid;

    public static String getCurUserUuid(HttpServletRequest request) {

        FleaSession fleaSession = new FleaSession();
        HttpSession session = fleaSession.getSession(request);
        ILoginInfo loginInfo = (ILoginInfo) session
                .getAttribute(ILoginInfo.ID_userInfoInSesion);
        userUuid = loginInfo == null ? null : loginInfo.getUserID();
        return userUuid;
    }

    public static String getUserNameByUserUuid(String userUuid) {
        String userName = "";
        OrgUser user = null;
        Map<String, Object> result = null;
        Object cacheObject = FleaCacheUtil.get("string_getUserNameByUserUuid_" + userUuid);
        if (null != cacheObject) {
            user = (OrgUser) cacheObject;
        } else {
            result = FleaWordServiceUtils.classService("orgUserService", IOrgUserService.class, "getUserByUuid", userUuid);
            Object obj = result.get("model");
            if (null != obj) {
                user = (OrgUser) obj;
                FleaCacheUtil.put("string_getUserNameByUserUuid_" + userUuid, user);
            }
        }

        if (null != user) {
            userName = user.getUserName();
        }
        return userName;
    }

    public static OrgUser getUserByUserUuid(String userUuid) {

        OrgUser user = null;
        Map<String, Object> result = null;
        Object cacheObject = FleaCacheUtil.get("string_getUserNameByUserUuid_" + userUuid);
        if (null != cacheObject) {
            user = (OrgUser) cacheObject;
        } else {
            result = FleaWordServiceUtils.classService("orgUserService", IOrgUserService.class, "getUserByUuid", userUuid);
            Object obj = result.get("model");
            if (null != obj) {
                user = (OrgUser) obj;
                FleaCacheUtil.put("string_getUserNameByUserUuid_" + userUuid, user);
            }
        }

        return user;
    }


    @SuppressWarnings("unchecked")
    public static boolean isSuperAdmin(String curUserUuid) {
        Map<String, Object> result = null;
        Object cacheObject = FleaCacheUtil.get(curUserUuid);
        if (null != cacheObject) {
            result = (Map<String, Object>) cacheObject;
        } else {
            result = FleaWordServiceUtils.classService("orgUserService", IOrgUserService.class, "getRoleByUseruuId",
                    curUserUuid);
            FleaCacheUtil.put(curUserUuid, result);
        }
        Object obj = result.get("model");
        if (null != obj) {
            List<OrgRole> roles = (List<OrgRole>) obj;
            for (OrgRole orgRole : roles) {
                if (orgRole.getRoleCode().equals("FleaSuperRole")) {
                    return true;
                }
            }

        } else {
            return false;
        }
        return false;
        /*
         * Method method = null; try { method =
         * OrgUserService.class.getMethod("getRoleByUseruuId", String.class);
         * ServletContext s =
         * ContextLoader.getCurrentWebApplicationContext().getServletContext();
         * WebApplicationContext context =
         * WebApplicationContextUtils.getWebApplicationContext(s);
         * IOrgUserService oo = (IOrgUserService)
         * context.getBean("orgUserService"); List<OrgRole> results =
         * oo.getRoleByUseruuId(curUserUuid);
         *
         * } catch (NoSuchMethodException | SecurityException e) {
         * e.printStackTrace(); return false; }
         */

    }

    public static OrgUser getCurUser(HttpServletRequest request) {
        String userid = getCurUserUuid(request);
        Map<String, Object> result = null;

        Object cacheObject = FleaCacheUtil.get(userid + "_getCurUser");
        if (null != cacheObject) {
            result = (Map<String, Object>) cacheObject;
        } else {
            result = FleaWordServiceUtils.classService(
                    "orgUserService", IOrgUserService.class, "getUserByUuid",
                    userid);
            FleaCacheUtil.put(userid + "_getCurUser", result);

        }
        if (null != result) {
            return (OrgUser) result.get("model");
        } else {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public static OrgDept getCurrentUserDept(HttpServletRequest request) {
        String userid = getCurUserUuid(request);
        Map<String, Object> result = null;

        Object cacheObject = FleaCacheUtil.get(userid + "_getCurrentUserDept");
        if (null != cacheObject) {
            result = (Map<String, Object>) cacheObject;
        } else {
            result = FleaWordServiceUtils.classService(
                    "orgDeptService", IOrgDeptService.class, "findDeptsByUserUuid",
                    userid);
            FleaCacheUtil.put(userid + "_getCurrentUserDept", result);
        }

        if (null != result) {
            List<OrgDept> depts = (List<OrgDept>) result.get("model");
            if (null != depts && depts.size() > 0) {
                return depts.get(0);
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    public static OrgDept getCurrentUserDept(String userUuid) {
        Map<String, Object> result = null;

        Object cacheObject = FleaCacheUtil.get(userUuid + "String_getCurrentUserDept");
        if (null != cacheObject) {
            result = (Map<String, Object>) cacheObject;
        } else {
            result = FleaWordServiceUtils.classService(
                    "orgDeptService", IOrgDeptService.class, "findDeptsByUserUuid",
                    userUuid);
            FleaCacheUtil.put(userUuid + "String_getCurrentUserDept", result);
        }
        if (null != result) {
            @SuppressWarnings("unchecked")
            List<OrgDept> depts = (List<OrgDept>) result.get("model");
            if (null != depts && depts.size() > 0) {
                return depts.get(0);
            } else {
                return null;
            }

        } else {
            return null;
        }
    }

    /**
     * 根据服务组织结构的uuid获取部门信息
     *
     * @param
     * @description TODO
     * @methodName getOrgDeptByDeptId
     * @returnType OrgDept
     * @throw
     */
    public static OrgDept getOrgDeptByDeptUuid(String uuid) {
        Map<String, Object> result = null;

        Object cacheObject = FleaCacheUtil.get(uuid + "OrgDept_getOrgDeptByDeptUuid");
        if (null != cacheObject) {
            result = (Map<String, Object>) cacheObject;
        } else {
            result = FleaWordServiceUtils.classService(
                    "orgDeptService", IOrgDeptService.class, "findByUUid",
                    uuid);
            FleaCacheUtil.put(uuid + "OrgDept_getOrgDeptByDeptUuid", result);
        }
        if (null != result) {
            OrgDept dept = (OrgDept) result.get("model");
            if (null != dept) {
                return dept;
            } else {
                return null;
            }

        } else {
            return null;
        }
    }


    /**
     * 获取当前用户的部门id
     *
     * @param
     * @description TODO
     * @methodName getCurrentUserDeptUuid
     * @returnType String
     * @throw
     */
    public static String getCurrentUserDeptUuid(HttpServletRequest request) {

        String userid = getCurUserUuid(request);
        Map<String, Object> result = null;

        Object cacheObject = FleaCacheUtil.get(userid + "String_getCurrentUserDeptUuid");
        if (null != cacheObject) {
            result = (Map<String, Object>) cacheObject;
        } else {

            result = FleaWordServiceUtils.classService(
                    "orgDeptService", IOrgDeptService.class, "findDeptsByUserUuid",
                    userid);
            FleaCacheUtil.put(userid + "String_getCurrentUserDeptUuid", result);
        }
        if (null != result) {
            @SuppressWarnings("unchecked")
            List<OrgDept> depts = (List<OrgDept>) result.get("model");
            if (null != depts && depts.size() > 0) {
                OrgDept temp = depts.get(0);
                if (null != temp) {
                    return temp.getDeptUuid();
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } else {
            return null;
        }

    }

    /**
     * 根据用户名称,模糊查询，获取用户列表
     *
     * @param
     * @description TODO
     * @methodName getUserByLikeName
     * @returnType String
     * @throw
     */
    public static List<OrgUser> getUserByLikeName(String name) {
        Map<String, Object> result = FleaWordServiceUtils.classService(
                "orgUserService", IOrgUserService.class, "findByLikeName",
                name);
        if (null != result) {
            @SuppressWarnings("unchecked")
            List<OrgUser> users = (List<OrgUser>) result.get("model");
            if (null != users && users.size() > 0) {
                return users;
            } else {
                return null;
            }
        } else {
            return null;
        }

    }

    /**
     * 根据用户名称，获取用户列表
     *
     * @param
     * @description TODO
     * @methodName getUserByExactName
     * @returnType String
     * @throw
     */
    public static List<OrgUser> getUserByExactName(String name) {
        Map<String, Object> result = FleaWordServiceUtils.classService("orgUserService", IOrgUserService.class, "findByExactName",
                name);
        if (null != result) {
            @SuppressWarnings("unchecked")
            List<OrgUser> users = (List<OrgUser>) result.get("model");
            if (null != users && users.size() > 0) {
                return users;
            } else {
                return null;
            }
        } else {
            return null;
        }

    }

    public static List<OrgDept> getDeptByLikeName(String name) {
        Map<String, Object> result = FleaWordServiceUtils.classService("orgDeptService", IOrgDeptService.class, "findByLikeName",
                name);
        if (null != result) {
            @SuppressWarnings("unchecked")
            List<OrgDept> orgDepts = (List<OrgDept>) result.get("model");
            if (null != orgDepts && orgDepts.size() > 0) {
                return orgDepts;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 根据用户userUuid和用户deptcode，添加用户部门关系
     *
     * @param userUuid
     * @param deptCode
     * @return
     */
    public static boolean addUserDept(String userUuid, String deptCode) throws Exception {
        Map<String, Object> result = FleaWordServiceUtils.classService("orgDeptUserService", IOrgDeptUserService.class, "saveIOrgDpetUserRelation",
                userUuid, deptCode);
        if (null != result) {
            boolean re = (boolean) result.get("model");
            return re;
        }
        return false;
    }

    /**
     * 根据用户uuid和 角色code，添加用户关系
     *
     * @param userUuid
     * @param roleCode
     * @return
     */
    public static boolean addUserRole(String userUuid, String roleCode) throws Exception {
        Map<String, Object> result = FleaWordServiceUtils.classService("orgRoleUserService", IOrgRoleUserService.class, "saveUserRoleRelation",
                userUuid, roleCode);
        boolean re = false;
        if (null != result) {
            re = (boolean) result.get("model");
            return re;
        }
        return re;
    }

    /**
     * 根据用户uuid 和角色code，更新用户role关系
     *
     * @param userUuid
     * @param oldRoleCode
     * @param newRoleCode
     * @return
     * @throws Exception
     */
    public static boolean updateUserRole(String userUuid, String oldRoleCode, String newRoleCode) throws Exception {
        Map<String, Object> result = FleaWordServiceUtils.classService("orgRoleUserService", IOrgRoleUserService.class, "updateUserRoleRelation",
                userUuid, oldRoleCode, newRoleCode);
        boolean re = false;
        if (null != result) {
            re = (boolean) result.get("model");
            return re;
        }
        return re;
    }

    /**
     * 是否为供应商
     *
     * @param orgDept
     * @return
     */
    public static boolean isSupplier(OrgDept orgDept) {
        if (null == orgDept) {
            return false;
        }
        if (HConstant.D_SERVICE_ORG_SUPPLIER.equals(orgDept.getServiceType())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 是否为组团社
     *
     * @param orgDept
     * @return
     */
    public static boolean isGroup(OrgDept orgDept) {
        if (null == orgDept) {
            return false;
        }
        if (HConstant.D_SERVICE_ORG_GROUP.equals(orgDept.getServiceType())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 是否为地接社
     *
     * @param orgDept
     * @return
     */
    public static boolean isGround(OrgDept orgDept) {
        if (null == orgDept) {
            return false;
        }
        if (HConstant.D_SERVICE_ORG_GROUND.equals(orgDept.getServiceType())) {
            return true;
        } else {
            return false;
        }
    }

}
